import {
  wxLogin,
  addComplaint
} from '../../request/api';
import Cache from "../../request/cache";
import timeFormate from '../../utils/timeFormate';
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName:'', 
    avatarUrl:'', 
    resData: [],
    // hasUserInfo:false,//没有登录
    islogin: false,
    menuData: [{
        name: '发布',
        url: '/pages/myOrder/index'
      },
      {
        text: "收藏",
        url: '/pages/MyFavorites/index'
      }
    ],
    options: [  
      { id: 1, name: '发布数量' },
      { id: 2, name: '我的收藏' }
    ] 
  },
  onLoad() {
    console.log('个人中心=============onLoad')
    // console.log('个人中心onLoad===========================1')
    // console.log('个人中心onLoad===========================2')
   // this.setUserInfo();
  },
  onShow(){
    console.log('个人中心=============onShow-1')
    //let token = Cache.getCache('token');
    //let token = wx.getStorageSync('token');
    //console.log('token:'+token.length)
    let userId = wx.getStorageSync('userId');
    console.log('本地userId:'+userId)
    if(userId.length < 1){
      console.log('userId不存在:'+userId)
      this.setData({
        islogin: false,
        nickName:"",
        avatarUrl: ""
      })
    }else{
      let nickName = wx.getStorageSync('nickName');
      let avatarUrl = wx.getStorageSync('avatarUrl');
        this.setData({
          islogin: true,//说明登录了
          nickName: nickName,
          avatarUrl: avatarUrl
        })
        console.log('获取完毕=======')
    }
    console.log('个人中心=============onShow-2')
  },
  onShareAppMessage() {
  },
  setUserInfo() {//获取本地信息
    console.log('获取本地信息======1')
    let token = wx.getStorageSync('token');
    let userId = wx.getStorageSync('userId');
    let nickName = wx.getStorageSync('nickName');
    let avatarUrl = wx.getStorageSync('avatarUrl');
    if(userId.length>0){
      this.setData({
        islogin: true,//说明登录了
        nickName: nickName,
        avatarUrl: avatarUrl
      })
    }
    

    //wx.setStorageSync('token',data.token); 
    //wx.setStorageSync('userId',data.userId); 
    //wx.setStorageSync('nickName',userInfo.nickName); 
    //wx.setStorageSync('avatarUrl',userInfo.avatarUrl); 
    // wx.showLoading({title: "正在登录...",mask: true})
    console.log('获取本地信息======2')
  },
  goToLoginUser() {//按钮触发登录
    // console.log('按钮触发登录======1')
    // wx.showLoading({title: "正在登录...",mask: true})
    // console.log('获取会员资料======1')
    wx.getSystemInfo({  
      success: function(res) {  
        var version = res.SDKVersion;  
        console.log("输出当前基础库版本号:"+version); // 输出当前基础库版本号  
      }  
    });
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res)
        // console.log('用于完善会员资料=======================');
        // console.log(res); // 输出当前基础库版本号  
        // console.log(res.userInfo); // 输出当前基础库版本号  
        let userInfo=res.userInfo
        if(res.errMsg === "getUserProfile:ok") {
          // console.log('解析微信返回数据=======================1');
          // let encryptedData = res.encryptedData;
          // let iv = res.iv;
          // let cloudID = res.cloudID;
          // let signature = res.signature;
             // 用户同意授权后，可以在这里获取到用户的昵称和头像  
          // console.log(res.userInfo.nickName); // 用户昵称  
          // console.log(res.userInfo.avatarUrl); // 用户头像  
          // console.log('解析微信返回数据=======================2');
          wx.login({
            success: async res => {
                if (res.errMsg === "login:ok") {
                  //发起后端请求
                  // console.log('维信登录==================code:'+res.code)
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                  const data = await wxLogin({
                    "code": res.code,
                    // "gender": userInfo.gender,
                    "nickName": userInfo.nickName,
                    "avatarUrl": userInfo.avatarUrl,
                    // "encryptedData":encryptedData,
                    // "iv": iv,
                    // "cloudID": cloudID,
                    // "signature": signature,
                    // "userInfo": userInfo
                  })
                  console.log('维信登录==================返回1')
                  console.log(data)
                  userInfo.nickName=data.nickName
                  //key, value, expire
                  // Cache.setCache("userId",data.userId, 3600);
                  // Cache.setCache("token",data.token, 3600);
                  wx.setStorageSync('token',data.token); 
                  wx.setStorageSync('userId',data.userId); 
                  wx.setStorageSync('nickName',data.nickName); 
                  wx.setStorageSync('avatarUrl',userInfo.avatarUrl); 
                  // console.log('维信登录==================返回1')
                  // console.log('设置到本地前=======================2');
                  // console.log(userInfo);
                  // console.log('设置到本地前=======================2');
                  this.setData({
                    islogin: true,
                    nickName: data.nickName,
                    userId: data.userId,
                    avatarUrl: userInfo.avatarUrl
                  })
                  // console.log('更新个人中心=======================信息');
                }
            },
            fail: res => {
              wx.showToast({icon: "error",title: "登录失败"});
              //wx.hideLoading();
            }
          })
        }else{
          // console.log('用于完善会员资料=======================拒绝了授权');
          wx.showToast({
            title: '拒绝了授权,无法完成登录',
          })
        }
      },
      fail: (err) => {  
        // 用户拒绝授权  
        console.error(err);  
        // 显示提示框告知用户  
        wx.showToast({  
          title: '您拒绝了授权，无法获取您的信息,将无法发布信息',  
          icon: 'none', // 不显示图标  
          duration: 2000 // 持续2秒  
        });  
        // 你还可以在这里做其他处理，比如跳转到某个页面或隐藏某些功能  
      }  
    })
  },
  loutOutUer(){
    //退出登录
    console.log('个人中心=============退出登录')
    wx.removeStorageSync('nickName');
    wx.removeStorageSync('token');
    wx.removeStorageSync('avatarUrl');
    wx.removeStorageSync('userId');
    this.setData({
      islogin:false,
      nickName: "",
      avatarUrl: ""
    })
    wx.showToast({
      title: '成功退出了登录',
    })
  },
  methods: {
    handleClick(e) {
      console.log(e.detail.file);
    },
  },
  showDialog(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log('key:',key)
    this.setData({
      [key]: true,
      dialogKey: key
    });
  },
  //async
  async sendDialog(e) {
    console.log(e)
    console.log('thisdata:',this.data)
    let uid = wx.getStorageSync('userId'); 
    let userName = wx.getStorageSync('userName'); 
    if (e.type == 'confirm') {
      await addComplaint({
        "context": this.data.complatinContext,
        "createBy": userName,
        "createTime": timeFormate(),
        "userId": uid,
        "userName": userName
      })
      wx.showToast({
        title: '提交成功！',
      })
    }
    const {
      dialogKey
    } = this.data;
    console.log('dialogKey:',dialogKey)
    this.setData({
      [dialogKey]: false
    });
  },
  closeDialog(e) {
    console.log(e)
    console.log('closeDialog=thisdata:',this.data)
    let key= 'showTextAndTitleWithInput'
    console.log('closeDialogKey:',key)
    this.setData({
      [key]: false
    });
  },
  inputHandler(e) {
    console.log(e)
    const {
      value
    } = e.detail;
    this.setData({
      complatinContext: value
    })
  },
  // ... 跳转其他页面逻辑  
  navigateToDetail: function(e) {  
        // 获取点击的item的id  
        var id = e.currentTarget.dataset.id;  
          console.log(id)
        // 根据id跳转到对应页面，这里假设有两个页面，分别是imageExtract和videoParse  
        if (id === 1) {  
          wx.navigateTo({  
            url: '../myOrder/index',
          });  
        } else if (id === 2) {  
          wx.navigateTo({  
            url: '../MyFavorites/index',  
          });  
        }  else if (id === 3) {  
          this.showDialog()
          // wx.navigateTo({  
          //   url: '/components/passwordgeneration/passwordgeneration'  
          // });  
        }  
  },
  gotomyOrder: function () {
    let userId = wx.getStorageSync('userId');
    console.log('本地userId:'+userId)
    if(userId.length < 1){
      wx.showToast({icon: "error",title: "请先完成登录"});
    }else{
      wx.navigateTo({
        url: '../myOrder/index',
      })
    }
  },
  gotoMyFavorites: function (options) {
    console.log('去搜藏页面')
    let userId = wx.getStorageSync('userId');
    console.log('本地userId:'+userId)
    if(userId.length < 1){
      wx.showToast({icon: "error",title: "请先完成登录"});
    }else{
      wx.navigateTo({
        url: '../MyFavorites/index',
      })
    }
    
  },
});